@using System.Text.Json
@rendermode InteractiveServer

<Table TItem="工单全信息视图" IsStriped="true" IsBordered="true" ShowAddButton="false" ShowEditButton="false"
    ShowDeleteButton="false" ShowExtendEditButton="false" ShowExtendDeleteButton="false" ShowToolbar="true"
    ShowDefaultButtons="false" ShowSearch="false" IsMultipleSelect="true" ShowExtendButtons="true" ShowLoading="true"
    OnQueryAsync="@OnQueryAsync"  @ref="@工单全信息视图table" IsPagination="true "   PageItemsSource="new int[] { 5, 10, 50, 100 }"
    
     @bind-SelectedRows="SelectedItems" >

    <TableToolbarTemplate>
        
   

        
        @if (HasPermissionForSelectedItems())
        {
            <TableToolbarButton TItem="工单全信息视图" Color="Color.Primary" 
                IsDisabled="@(SelectedItems == null || SelectedItems.Any(cm => cm.当前状态 != WorkOrderStatus.待分派))"
            Icon="fa-fw fa-solid fa-floppy-disk" Text="批量分派"
            IsAsync="true" OnClickCallback="@BatchAssignment" />
        }

    </TableToolbarTemplate>
    <TableColumns>

        <TableColumn @bind-Field="@context.优先级" Filterable="true" Width="100" >
            <Template Context="value">
                @{
                    switch (value.Row.优先级)
                    {
                        case  PriorityLevel.低:
                            <Badge IsPill="true" Color="Color.Secondary">@value.Value</Badge>
                            ;
                            break;
                        case PriorityLevel.正常:
                            <Badge IsPill="true" Color="Color.Success">@value.Value</Badge>
                            ;
                            break;
                        case  PriorityLevel.高:
                            <Badge IsPill="true" Color="Color.Warning">@value.Value</Badge>
                            ; 
                            break;
                        case  PriorityLevel.紧急:
                            <Badge IsPill="true" Color="Color.Danger">@value.Value</Badge>
                            ;
                            break;
                    }

                }
            </Template>
        </TableColumn>
        <TableColumn @bind-Field="@context.工单编号"  Filterable="true" ></TableColumn>
        @* <TableColumn @bind-Field="@context.工单标题"></TableColumn> *@
        <TableColumn @bind-Field="@context.扩展字段" Text="表单内容">
            <Template Context="value">
            @if (value.Value != null)
            {
                <pre>@string.Join(Environment.NewLine, value.Value.Select(kvp => $"{kvp.Key}: {kvp.Value}"))</pre>
            }
            </Template>
        </TableColumn>
        <TableColumn @bind-Field="@context.创建人ID"   Filterable="true"></TableColumn>
        <TableColumn @bind-Field="@context.截止时间" Filterable="true" Sortable="true"   ></TableColumn>
        <TableColumn @bind-Field="@context.创建时间" Filterable="true" Sortable="true" DefaultSort="true"  DefaultSortOrder="@SortOrder.Desc"></TableColumn>
        <TableColumn @bind-Field="@context.更新时间" Filterable="true" Sortable="true"></TableColumn>
        <TableColumn @bind-Field="@context.关闭时间"></TableColumn>
        <TableColumn @bind-Field="@context.总金额"></TableColumn>
        <TableColumn @bind-Field="@context.负责人id列表"  Filterable="true"  ></TableColumn>
        <TableColumn @bind-Field="@context.评论数量"></TableColumn>
        <TableColumn @bind-Field="@context.附件数量"></TableColumn>
        <TableColumn @bind-Field="@context.当前状态" Filterable="true" Sortable="true" Width="100"> 
            <Template Context="value">
                @{
                    switch (value.Row.当前状态)
                    {
                        case  WorkOrderStatus.待处理:
                            <Badge IsPill="true" Color="Color.Warning">@value.Value</Badge>
                            ;
                            break;
                        case  WorkOrderStatus.待分派:
                            <Badge IsPill="true" Color="Color.Warning">@value.Value</Badge>
                            ;
                            break;
                        case WorkOrderStatus.已分派:
                            <Badge IsPill="true" Color="Color.Info">@value.Value</Badge>
                            ;
                            break;
                        case WorkOrderStatus.处理中:
                            <Badge IsPill="true" Color="Color.Primary">@value.Value</Badge>
                            ;
                            break;
                        case WorkOrderStatus.已解决:
                            <Badge IsPill="true" Color="Color.Success">@value.Value</Badge>
                            ;
                            break;
                        case WorkOrderStatus.已关闭:
                            <Badge IsPill="true" Color="Color.Dark">@value.Value</Badge>
                            ;
                            break;
                        case WorkOrderStatus.重新打开:
                            <Badge IsPill="true" Color="Color.Danger">@value.Value</Badge>
                            ;
                            break;
                        case WorkOrderStatus.审核中:
                            <Badge IsPill="true" Color="Color.Secondary">@value.Value</Badge>
                            ;
                            break;
                    }
                }
            </Template>
        </TableColumn>


    </TableColumns>
    <RowButtonTemplate>
        <TableCellButton Color="Color.Info" Icon="fa-solid fa-eye" Text="明细"
            OnClick="@(() => ShowAccountDetails(context))" />
 
            @if (context.当前状态 != WorkOrderStatus.已解决 && context.当前状态 != WorkOrderStatus.已关闭)
            {
                @if(HasPermissionForSelectedItems(context)){
                <TableCellButton Color="Color.Warning" Icon="fa-solid fa-wrench" Text="处理"
                OnClick="@(() => ShowTicketProcessHandler(context))" />
                }
           
            }
            <TableCellButton Color="Color.Success" Icon="fa-solid fa-copy" Text="复制内容"
                OnClick="@(() => CopyTicketDetails(context))" />
    </RowButtonTemplate>
</Table>



@code {
    [Inject]
    [NotNull]
    private ClipboardService? ClipboardService { get; init; }
    [Inject]
    [NotNull]
    private ToastService? ToastService { get; set; }
    [Inject]
    [NotNull]
    private DialogService? DialogService { get; set; }
    [Parameter]
    public EventCallback<int> OnTotalCountChanged { get; set; }
    [Inject]
    [NotNull]
    private MyIdentityContext? AppContext { get; set; }

    [Inject]
    [NotNull]
    private IWorkOrderService WorkOrderService { get; set; }

     private bool IsAssignedToCurrentUser { get; set; } = false;

    private 工单流程实例表? ProcessInstance { get; set; }
    private 流程节点表? CurrentNode { get; set; } 

 
    private bool hasApprovalPermission { get; set; } = false;

    [Inject]
    private IUser   UserService { get; set; } 

    private Table<工单全信息视图>? 工单全信息视图table { get; set; } = null!;
    [NotNull]
    private List<工单全信息视图>? SelectedItems { get; set; }= new List<工单全信息视图>();
    [Parameter]
    [NotNull]
    public string? FilterType { get; set; }

    [Inject]
    [NotNull]
    private ISystemNotificationService SystemNotificationService { get; set; }
    private async Task ShowTicketProcessHandler(工单全信息视图 item)
    {
        try
        {


                var option = new DialogOption()
                {
                    Title = $"处理工单 - 当前工单: {item.工单ID}",
                    Size = Size.ExtraLarge, // 建议调整对话框尺寸
                    Component = BootstrapDynamicComponent.CreateComponent<TicketProcessHandler>(new Dictionary<string, object?>
                    {
                        [nameof(TicketProcessHandler.TicketID)] = item.工单ID
                    }),OnCloseAsync = async () =>
                    {    

                        await  工单全信息视图table.QueryAsync();   
                        // 关闭对话框时的操作
                        await Task.CompletedTask;
                    }
                };

            await DialogService.Show(option);
            // 通知 Blazor 重新渲染组件
        }
        catch (Exception ex)
        {
            // 处理异常，例如显示错误提示
            await ToastService.Error("加载失败", ex.Message);
        }
    }

    private async Task ShowAccountDetails(工单全信息视图 item)
    {
        try
        {


            var option = new DialogOption()
            {
                Title = $"查看工单详情 - 当前工单: {item.工单ID}",
                Size = Size.ExtraLarge, // 建议调整对话框尺寸
                Component = BootstrapDynamicComponent.CreateComponent<TicketlistDetail>(new Dictionary<string, object?>
                {
                    [nameof(TicketlistDetail.TicketID)] = item.工单ID
                })
                ,OnCloseAsync = async () =>
                {      

                    await  工单全信息视图table.QueryAsync();
                    // 关闭对话框时的操作
                    await Task.CompletedTask;
                }
                


            };

            await DialogService.Show(option);
        }
        catch (Exception ex)
        {
            // 处理异常，例如显示错误提示
            await ToastService.Error("加载失败", ex.Message);
        }
    }

    private async Task CopyTicketDetails(工单全信息视图 item)
    {
        try
        {
            // 获取工单详情
          

            // 格式化内容
            var content = string.Join(Environment.NewLine, item.扩展字段.Select(kvp => $"{kvp.Key}: {kvp.Value}"));

            // 调用 JavaScript 将内容复制到剪切板
            await ClipboardService.Copy(content);
            // 显示成功提示
            await ToastService.Success("复制成功", "工单详情已复制到剪切板！");
        }
        catch (Exception ex)
        {
            // 显示错误提示
            await ToastService.Error("复制失败", ex.Message);
        }
    }

    private async Task<QueryData<工单全信息视图>> OnQueryAsync(QueryPageOptions options)
    {
 
        List<工单全信息视图> mole = FilterType switch
        {
            "我的未处理工单" => await WorkOrderService.GetWorkOrdersForUserAsync(AppContext.UserName,WorkOrderStatus.处理中),
            "与我相关的工单" => await WorkOrderService.GetWorkOrdersForMeAsync(AppContext.UserName),
            "工单list" => await WorkOrderService.GetWorkOrdersAsync(),
            "我的历史完成工单" => await WorkOrderService.GetWorkOrdersForUserCompletedAsync(AppContext.UserName),
            _ => new List<工单全信息视图>() // 默认返回空列表
        };
        // 模拟查询数据
        var ret = new QueryData<工单全信息视图>()
        {
            IsSorted = true,
            IsFiltered = true,
            IsSearch = true,
            IsAdvanceSearch = true
        };


        // 处理模糊查询
        var filters = options.Filters.Concat(options.Searches).Concat(options.CustomerSearches);
        if (options.IsPage)
        {

            var items = mole.AsQueryable()
            .Where(filters.GetFilterLambda<工单全信息视图>(), filters.Any())
            .Sort(options.SortName!, options.SortOrder, !string.IsNullOrEmpty(options.SortName))
            .Count(out var count)
            .Page((options.PageIndex - 1) * options.PageItems, options.PageItems);
            ret.TotalCount = count;
            ret.Items = items;
        }
        else
        {
            var items = mole.AsQueryable()
            .Where(filters.GetFilterLambda<工单全信息视图>(), filters.Any())
            .Count(out var count);
            ret.TotalCount = count;
            ret.Items = items;
        }
        if (options.AdvanceSearches.Any())
        {
            var items = mole.AsQueryable()
            .Where(options.AdvanceSearches.GetFilterFunc<工单全信息视图>());
            ret.TotalCount = items.Count();
            ret.Items = items;
        }
        if (options.Searches.Any())
        {
            var items = mole.AsQueryable()
            .Where(options.Searches.GetFilterFunc<工单全信息视图>(FilterLogic.Or));
            ret.TotalCount = items.Count();
            ret.Items = items;

        }
        
         await OnTotalCountChanged.InvokeAsync(ret.TotalCount);

        return await Task.FromResult(ret);
    }


    private async Task BatchAssignment(IEnumerable<工单全信息视图> items)
    {
        if (!items.Any())
        {
            await ToastService.Error("失败", "没有选中任何工单！");
            return;
        }

        if (items.Select(item => item.当前节点ID).Distinct().Count() > 1)
        {
            await ToastService.Error("失败", "所选工单不在同一个节点！");
            return;
        }


        // 创建选择器组件参数
        var parameters = new Dictionary<string, object?>
        {
            [nameof(Select<string>.Items)] =await GetUserItems(items.FirstOrDefault().工单ID), // 获取用户选项
            [nameof(Select<string>.IsClearable)] = true,
            [nameof(Select<string>.ShowSearch)] = true,
            [nameof(Select<string>.OnSelectedItemChanged)] = new Func<SelectedItem, Task>(async item =>
    {
        _selectedValue = item.Value;
          HandleSelectionChanged(item);
    })
        };

        // 创建对话框配置
        var option = new DialogOption()
        {
            Title = "批量分派工单",
            Size = Size.ExtraLarge,
            Component = BootstrapDynamicComponent.CreateComponent<Select<string>>(parameters),
            ShowSaveButton = true,
            OnSaveAsync = async () =>
            {
                if (string.IsNullOrEmpty(_selectedValue))
                {
                    await ToastService.Warning("请先选择处理人");
                    return false;
                }
                try
                {
                    foreach (var item in items)
                    {
                        if (item.工单ID != null && AppContext.UserName != null)
                        {
                            await WorkOrderService.ChangeAssigneeAsync(item.工单ID, new List<string> { _selectedValue }, AppContext.UserName, "分派工单给处理人");
                            await ToastService.Success("分派成功", $"工单 {item.工单ID} 已分派给 {_selectedValue}！");
                            await SystemNotificationService.SendNotificationAsync(Constant.UserMessagge, DispatchType.Toast,"成功",$"{item.创建人ID}创建的工单已被{AppContext.UserName}分配给您请尽快处理",_selectedValue);  
                        }
                        else
                        {
                            await ToastService.Error("分派失败", "工单ID或操作用户不能为空！");
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    await ToastService.Error("分派失败", ex.Message);
                    return false;
                }
            },OnCloseAsync = async () =>
                {  
                  await  工单全信息视图table.QueryAsync();
                    // 关闭对话框时的操作
                    await Task.CompletedTask;
                }
        };

        // 显示对话框
        await DialogService.Show(option);
    }
    // 选择变化处理
    private string? _selectedValue = string.Empty;
    private void HandleSelectionChanged(SelectedItem item)
    {
        _selectedValue = item.Value;
    }
   
    private async Task<List<SelectedItem>> GetUserItems(string x)
    {
    
    var permissionInfo = await WorkOrderService.GetProcessInstanceByWorkOrderIdAsync(x);
    var 下一节点 = permissionInfo?.当前节点?.源节点?.FirstOrDefault();
    if (下一节点 == null) return new List<SelectedItem>();

    var 节点详情 = await WorkOrderService.GetRoute(下一节点.目标节点ID);
    if (节点详情 == null) return new List<SelectedItem>();

    // 2. 根据下一节点的负责人规则筛选用户
    switch (节点详情.负责人规则类型)
    {
        case AssignRuleType.角色:
            return UserService.GetUsersByRoleName(节点详情.负责人规则参数)?.ToSelectedItemList2() ?? new List<SelectedItem>();

        default:
            return UserService.GetAll()?.ToSelectedItemList2() ?? new List<SelectedItem>();
    }

    }
 private bool HasPermissionForSelectedItems()
{
    if (SelectedItems == null || !SelectedItems.Any())
    {
        return false;
    }

    foreach (var item in SelectedItems)
    {
        // 获取工单流程实例
        var processInstance =  WorkOrderService.GetProcessInstanceByWorkOrderId(item.工单ID);

        // 获取当前节点的权限
        if (processInstance?.当前节点 != null)
        {
            var hasPermission = processInstance.当前节点.负责人规则类型 switch
            {
                AssignRuleType.角色 => AppContext.Roles.Contains(processInstance.当前节点.负责人规则参数),
                AssignRuleType.指定用户 => processInstance.当前节点.负责人规则参数 == AppContext.UserName,
                _ => false
            };

            // 如果有一个工单满足权限条件，返回 true
            if (hasPermission || AppContext.Roles.Contains("Administrator"))
            {
                return true;
            }
        }
    }

    // 如果所有工单都不满足权限条件，返回 false
    return false;
}
 private bool HasPermissionForSelectedItems(工单全信息视图 item)
{
  

   
        // 获取工单流程实例
        var processInstance =  WorkOrderService.GetProcessInstanceByWorkOrderId(item.工单ID);

        // 获取当前节点的权限
        if (processInstance?.当前节点 != null)
        {
            var hasPermission = processInstance.当前节点.负责人规则类型 switch
            {
                AssignRuleType.角色 => AppContext.Roles.Contains(processInstance.当前节点.负责人规则参数),
                AssignRuleType.指定用户 => processInstance.当前节点.负责人规则参数 == AppContext.UserName,
                _ => false
            };

            // 如果有一个工单满足权限条件，返回 true
            if (hasPermission || AppContext.Roles.Contains("Administrator"))
            {
                return true;
            }
        }


    // 如果所有工单都不满足权限条件，返回 false
    return false;
}
}